package com.example.adminvue.controller;

import com.example.adminvue.config.ParamConfig;
import com.example.adminvue.domain.AjaxResult;
import com.example.adminvue.domain.BGoods;
import com.example.adminvue.domain.TableDataInfo;
import com.example.adminvue.service.BGoodsService;
import com.example.adminvue.utils.FileUploadUtils;
import com.example.adminvue.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/web/goods")
public class BGoodsController extends BaseController
{
    @Autowired
    private BGoodsService bGoodsService;

    @GetMapping("/list")
    public TableDataInfo list(BGoods goods)
    {
        startPage();
        List<BGoods> list = bGoodsService.selectList(goods);
        TableDataInfo rspData = getDataTable(list);
        return rspData;
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return AjaxResult.success(bGoodsService.selectById(id));
    }

    @PostMapping
    public AjaxResult add(@Validated @RequestBody BGoods goods)
    {
        goods.setCreateBy(getUsername());
        return toAjax(bGoodsService.insert(goods));
    }

    @PutMapping
    public AjaxResult edit(@Validated @RequestBody BGoods goods)
    {
        return toAjax(bGoodsService.update(goods));
    }

    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable("id") Long[] id)
    {
        return toAjax(bGoodsService.deleteById(id));
    }

    @PostMapping("upload")
    public AjaxResult upload(MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            String goodsImg = FileUploadUtils.upload(ParamConfig.getUploadPath(), file);
            if (!StringUtils.isEmpty(goodsImg))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("goodsImg", goodsImg);
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

}
